﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using devtm.Collections;
using System.IO;
using System.Reflection;
using devtm.Helpers;
using System.Windows.Forms;

namespace devtm.Types.LazyLoading
{

    public class AssemblyGacNamespace : AssemblyNamespace
    {


        
        /// <summary>
        /// Initializes a new instance of the <see cref="AssemblyGacNamespace"/> class.
        /// </summary>
        /// <param name="item">The item.</param>
        public AssemblyGacNamespace(AssemblyDescription item)
            : base()
        {

            //this.Dirs = LazyLoadingHelper.Directories;
            IsFile = false;
            SingleName = item.AssemblyName;
            Name = item.ToSmallString();
            this.Filename = item.ToString();
            this.item = item;

            LoadReferences();

        }

        private void LoadReferences()
        {

            if (ReferencesLoaded)
                return;

            Assembly ass = Assembly.ReflectionOnlyLoad(Filename);
            System.Reflection.AssemblyName[] names = ass.GetReferencedAssemblies();

            foreach (System.Reflection.AssemblyName name in names)
            {
                AssemblyDescription desc = new AssemblyDescription(name.FullName);
                desc.HashCode = name.GetHashCode();
                this.References.Add(desc);
            }

            ReferencesLoaded = true;

        }

        private AssemblyDescription item;

        public override void Initialize()
        {
            if (this.Initialized || IsInError)
                return;
            
            try
            {
                Assembly ass = System.Reflection.Assembly.ReflectionOnlyLoad(item.ToString());

                this.Version = ass.ImageRuntimeVersion;
                this.Initialized = true;
                IsInError = false;
            }
            catch (Exception ex)
            {

                IsInError = true;
                if (!MixedMessage)
                if (ex.Message.StartsWith("Mixed mode assembly is built against version"))
                {
                    MixedMessage = true;

                    MessageBox.Show(
                        ex.Message, 
                        "Error", 
                        MessageBoxButtons.OK, 
                        MessageBoxIcon.Warning);
                    
                    return;
                }
                
            }

            

        }



        public static bool MixedMessage;

    }

}
